package com.tzvtc.server.students.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tzvtc.server.commons.bean.PageRequestBean;
import com.tzvtc.server.commons.exception.NormalException;
import com.tzvtc.server.commons.security.SecurityLocal;
import com.tzvtc.server.students.bean.StudentBean;
import com.tzvtc.server.students.mapper.StudentMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class StudentService {


    private final StudentMapper studentMapper;

    public StudentService(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }


    public PageInfo<StudentBean> list(PageRequestBean<StudentBean> pageRequestBean) {

        // select * from students where s_name='';
        // 帮我我们计算分页， 并且补充分页需要的sql关键字
        // select * from students where s_name = '' limit 20, 10;
        // 帮助我们查询符合条件的数据的数量
        // select count(id) from students where s_name = '';
        PageHelper.startPage(pageRequestBean.getPageNum(),pageRequestBean.getPageSize());
        List<StudentBean> list = studentMapper.select(pageRequestBean.getParams());

        return new PageInfo<>(list);
    }
    public void remove(StudentBean studentBean) {

        if(studentBean.getId() == null) {
            throw new NormalException("ID不能为空");
        }
        System.out.println(studentBean);
        int rows = studentMapper.delete(studentBean);
        if(rows <= 0) {
            throw new NormalException("删除失败");
        }
    }

    public void insert(StudentBean studentBean) {

        log.debug("学生信息保存, 检查参数完整性");
        if(studentBean == null) {
            throw new NormalException("学生姓名不能为空");
        }
        if(studentBean.getAge() == null || studentBean.getAge() <= 0) {
            throw new NormalException("学生年龄不能为空");
        }
        if(studentBean.getGender() == null ) {
            throw new NormalException("学生性别不能为空");
        }

        if (studentBean.getId() != null) {
            int updated = studentMapper.update(studentBean);
            if (updated<=0){
                throw new NormalException("保存失败");
            }
            return;
        }

        log.debug("学生信息保存, 补充参数");
        studentBean.setId(IdUtil.getSnowflakeNextId());

        log.debug("学生信息保存, 执行操作");
        int updated = studentMapper.insert(studentBean);
        if(updated <= 0) {
            throw new NormalException("学生信息保存失败");
        }
    }

    public StudentBean info(StudentBean studentBean){
        log.debug("学生信息详情,检查参数完整性");
        if (studentBean.getId() == null) {
            throw new NormalException("id不能为空");
        }
        return studentMapper.selectOne(studentBean);
    }
}
